<template>
    <footer>
        <div class="footer_left">
            <input ref="myRef" type="checkbox" id="done" @click="checkedAllToDoList"/>已完成<span class="done">{{ doneTaskNumber }}</span>/全部<span class="all">{{userTaskItem.length}}</span>
        </div>
        <div class="footer_right">
            <button id="del_done" @click="delAllDoneTask">清除已完成任务</button>
        </div>
    </footer>
</template>

<script>
import { inject,ref,computed,watch } from 'vue'

export default {
    name:'Footer',
    setup(props,{emit}) {
      let userTaskItem = inject('userTaskItem')
      const myRef = ref(null);      

      /* 全选 */ 
      function checkedAllToDoList(){
        emit('checkedAllToDoList', myRef.value.checked)        
      }

      /* 已完成任务数量 */  
      const doneTaskNumber = computed(() => {
       return userTaskItem.value.filter(v=>v.done===true).length 
      })

      /* 判断是否全选 */  
      watch(doneTaskNumber, (newValue) => {
        if(newValue!==0 && newValue===userTaskItem.value.length){
            myRef.value.checked=true
        }else{
            myRef.value.checked=false
        }
      })

      /* 添加任务时重置全选为false */
      watch(userTaskItem, (newValue) => {
        if(newValue.length>doneTaskNumber.value){
            myRef.value.checked=false
        }else if(newValue.length!==0 && newValue.length===doneTaskNumber.value){
            myRef.value.checked=true
        }else{
            myRef.value.checked=false 
        }
      },{deep:true})


      /* 清除所有已完成的任务 */
      function delAllDoneTask(){
        if(userTaskItem.value.length===0) return
        if (!confirm('确认要删除该任务吗?')) return
        emit('delAllDoneTask', delAllDoneTask)        
      }

      return{
        userTaskItem,
        doneTaskNumber,
        checkedAllToDoList,
        myRef,
        delAllDoneTask        
      }
    }
}
</script>

<style scoped>
footer{
    width: 100%;
    height: 50px;
    float: left;
    line-height: 50px;
}

.footer_left{    
    float: left;
    padding-left: 10px;
    box-sizing: border-box; 
}

.footer_left input{    
    margin-right: 20px;    
}

.footer_right{
    float: right;
}
    
.footer_right button{
    padding: 0 20px;
    height: 40px;
    line-height: 40px;
    color: #fff;
    background-color: #D5514C;
    border-radius: 5px;
    border: none;
    cursor: pointer;
}
</style>